﻿using Microsoft.EntityFrameworkCore.Query.Internal;
using SheepStorage.Domain;
using SheepStorage.Domain.DTO.Output;
using SheepStorage.Domain.Entity;
using SheepStorage.Domain.Enum;
using SheepStorage.Repository.BaseImp;
using SheepStorage.Repository.Interface;
using SheepStorage.Service.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yitter.IdGenerator;

namespace SheepStorage.Service.DataImp
{
    public class SheepMomPergnantService : ISheepMomPergnantService
    {

        private readonly IBaseRepository<SheepMomPergnant> pergnant;
        private readonly IBaseRepository<BuildingManagement> management;
        private readonly IBaseRepository<SheepField> sheepfield;
        private readonly IBaseRepository<SheepRecord> record;
        private readonly IBaseRepository<EarTagTable> eartag;
        private readonly IBaseRepository<SheepMomHistory> history;
        private readonly IBaseRepository<SheepChangeDormitory> dormitory;
        public SheepMomPergnantService(IBaseRepository<SheepMomPergnant> pergnant, IBaseRepository<BuildingManagement> management,
            IBaseRepository<SheepField> sheepfield, IBaseRepository<SheepRecord> record,
            IBaseRepository<EarTagTable> eartag, IBaseRepository<SheepMomHistory> history,
           IBaseRepository<SheepChangeDormitory> dormitory)
        {
            this.pergnant = pergnant;
            this.management = management;
            this.sheepfield = sheepfield;
            this.record = record;
            this.eartag = eartag;
            this.history = history;
            this.dormitory = dormitory;
        }
        /// <summary>
        /// 种母妊娠
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        /// <param name="OverBit"></param>
        /// <param name="MomPergnantPrincipal"></param>
        /// <param name="MomPergnantResult"></param>
        /// <param name="MomPergnantCount"></param>
        /// <returns></returns>

        public async Task<List<SheepMomPergnantDto>> GetSheepMomPergnant(string? startTime, string? endTime, string? OverBit, string? MomPergnantPrincipal, int? MomPergnantResult, int? MomPergnantCount)
        {



            var list = (from pergnant in pergnant.GetAll()
                        join management in management.GetAll()
                        on pergnant.BuildingManagementId equals management.BuildingManagementId into mg
                        from management in mg.DefaultIfEmpty()
                        join sheepfield in sheepfield.GetAll()
                        on pergnant.SheepFieldId equals sheepfield.SheepFieldId into sf
                        from sheepfield in sf.DefaultIfEmpty()
                        where pergnant.IsDel == 1
                        && (string.IsNullOrWhiteSpace(startTime) || pergnant.MomPergnantDate <= DateTime.Parse(startTime))
                        && (string.IsNullOrWhiteSpace(endTime) || pergnant.MomPergnantDate >= DateTime.Parse(endTime))
                        && (string.IsNullOrWhiteSpace(OverBit) || pergnant.OverBit.Contains(OverBit))
                         && (string.IsNullOrWhiteSpace(MomPergnantPrincipal) || pergnant.MomPergnantPrincipal == MomPergnantPrincipal)
                        && (MomPergnantResult == 0 || pergnant.MomPergnantResult == (MomPergnantResult))
                        && (MomPergnantCount == 0 || pergnant.MomPergnantCount == MomPergnantCount)
                        select new SheepMomPergnantDto()
                        {
                            MomPergnantCount = pergnant.MomPergnantCount,
                            MomPergnantResult = pergnant.MomPergnantResult,
                            OverBit = pergnant.OverBit,
                            AddName = pergnant.AddName,
                            AddTime = pergnant.AddTime,
                            DeliveryDocuument = pergnant.DeliveryDocuument,
                            DelName = pergnant.DelName,
                            DelTime = pergnant.DelTime,
                            ElEarTag = pergnant.ElEarTag,
                            IsDel = pergnant.IsDel,
                            MomPergnantDate = pergnant.MomPergnantDate,
                            MomPergnantGestation = pergnant.MomPergnantGestation,
                            MomPergnantId = pergnant.MomPergnantId,
                            MomPergnantPrincipal = pergnant.MomPergnantPrincipal,
                            MomPergnantRemark = pergnant.MomPergnantRemark,
                            MomPergnantType = pergnant.MomPergnantType,
                            PurchaseSerialNumber = pergnant.PurchaseSerialNumber,
                            Remarks = pergnant.Remarks,
                            UpdateName = pergnant.UpdateName,
                            UpdateTime = pergnant.UpdateTime,
                            //转入栋舍
                            BuildingManagementId = pergnant.BuildingManagementId,
                            BuildingManagementIdName = management.BuildingName,
                            //转入栏位
                            SheepFieldId = pergnant.SheepFieldId,
                            SheepFieldIdName = sheepfield.SheepFieldName,

                            //当前栋舍Id以及名称
                            MomPergnantBuilding = management.BuildingManagementId,
                            MomPergnantBuildingName = management != null ? management.BuildingName : null,
                            //当前栏位Id以及名称
                            MomPergnantField = sheepfield.SheepFieldId,
                            MomPergnantFieName = sheepfield != null ? sheepfield.SheepFieldName : null,
                        }).ToList();
            return list;
        }




        /// <summary>
        /// 种母妊娠添加
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async Task<int> AddSheepMomPergnant(List<SheepMomPergnant> sheepMomPergnant)
        {
            foreach (var m in sheepMomPergnant)
            {
                //雪花Id赋值单据号
                m.DeliveryDocuument = YitIdHelper.NextId().ToString();
                //雪花Id赋值流水号
                m.PurchaseSerialNumber = YitIdHelper.NextId().ToString();
                m.AddName = "管理员";
                m.AddTime = DateTime.Now;
                m.IsDel = 1;

                var lists = record.GetAll().FirstOrDefault(s => s.SheepRecordId == int.Parse(m.OverBit));
                m.OverBit = lists.OverBit;

                var result = pergnant.Add(m);
                if (result > 0)
                {
                    if (m.OverBit != null)
                    {
                        var list = record.GetAll().FirstOrDefault(s => s.SheepRecordId == lists.SheepRecordId);
                        list.SheepRecordBreedState = 7;
                        list.SheepRecordGestation = 1;
                        list.BuildingName = management.GetAll().FirstOrDefault(x => x.BuildingManagementId == m.BuildingManagementId).BuildingName;
                        list.SheepFieldName = sheepfield.GetAll().FirstOrDefault(x => x.SheepFieldId == m.SheepFieldId).SheepFieldName;
                        record.Update(list);

                        var his = history.GetAll().FirstOrDefault(s => s.OverBit == m.OverBit);
                        his.MomHistoryPregnantDate = m.MomPergnantDate;
                        his.MomHistoryPregnantResult = m.MomPergnantResult;
                        history.Update(his);

                        var sheepChangeDormitory = new SheepChangeDormitory()
                        {
                            AddName = "王小小",
                            AddTime = DateTime.Now,
                            OverBit = m.OverBit,
                            ChangedormitoryType = 3,
                            DocumentNumber = YitIdHelper.NextId().ToString(),
                            ElEarTag = m.OverBit,
                            IsDel = 0,
                            SerialNumber = YitIdHelper.NextId().ToString(),
                            SheepSex = false,
                            SheepType = 1,
                            RollOutField = m.MomPergnantField,
                            TransferOutDormitory = m.MomPergnantBuilding,
                            Auditor = null,
                            AuditTime = null,
                            ChangeRemark = null,
                            DelName = null,
                            DelTime = null,
                            Remarks = null,
                            UpdateName = null,
                            UpdateTime = null,
                            ChangedormitoryDate = DateTime.Now,
                            ChangeState = 0,
                            DriveField = m.SheepFieldId,
                            TransferToDormitory = m.BuildingManagementId,
                            Variety = eartag.GetAll().FirstOrDefault(s => s.OverBit == m.OverBit).BirType,
                        };
                        dormitory.Add(sheepChangeDormitory);

                    }

                }
            }
            return 1;
        }
        /// <summary>
        /// 删除种母妊娠信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<int> DelSheepMomPergnant(int MomPergnantId)
        {
            var list = pergnant.GetAll().FirstOrDefault(s => s.MomPergnantId == MomPergnantId);
            list.DelName = "管理员";
            list.DelTime = DateTime.Now;
            list.IsDel = 0;
            var result = pergnant.Update(list);
            if (result > 0)
            {
                //根据选中的耳号查询
                var ear = eartag.GetAll().FirstOrDefault(s => s.OverBit == list.OverBit);
                //修改耳号状态，（使用的耳号不能再次使用）
                ear.UseState = 2;
                eartag.Update(ear);
            }
            return result;
        }
        /// <summary>
        ///反填种母妊娠信息
        /// </summary>
        /// <param name="MomPergnantId"></param>
        /// <returns></returns>
        public async Task<SheepMomPergnant> BackfillSheepMomPergnant(int MomPergnantId)
        {
            var list = pergnant.GetInfoBy(MomPergnantId);
            return list;
        }
        /// <summary>
        /// 修改种母妊娠信息
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        public async Task<int> UpdateSheepMomPergnant(SheepMomPergnant m)
        {
            m.UpdateName = "管理人";
            m.UpdateTime = DateTime.Now;
            return pergnant.Update(m);
        }


    }
    
}

